package org.shop.oauth.demo.service;

import org.shop.oauth.demo.dao.AuthorityDao;
import org.shop.oauth.demo.dao.CredentialsDao;
import org.shop.oauth.demo.entity.Authority;
import org.shop.oauth.demo.entity.Credentials;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    ClientDetailsService clientDetailsService;


    @Autowired
    private CredentialsDao credentialsDao;
    @Autowired
    private AuthorityDao authorityDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Credentials credentials1=new Credentials();
        credentials1.setName(username);
        Credentials credentials = credentialsDao.selectOne(credentials1);
        if (credentials == null) {
            throw new UsernameNotFoundException("User '" + username + "' can not be found");
        }else{
            List<Authority> authorities=authorityDao.getAuthroitiesByCredential(credentials.getId());
            credentials.setAuthorityList(authorities);
        }

        return new User(credentials.getName(), credentials.getPassword(),credentials.getEnabled().equals("1")?true:false, true, true, true, credentials.getAuthorityList());
    }

}
